package com.wpp.mq.rabbitmqsqmple.workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.wpp.mq.rabbitmqsqmple.common.Constant;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @description: 消费者
 * @author: WangPengPeng
 * @create: 2021-11-28 20:34
 **/
public class Worker {
    private static final String TASK_QUEUE_NAME = "taskQueue";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务器主机名或IP地址
        factory.setHost(Constant.HOST);
        // 设置Erlang的虚拟主机名称
        factory.setVirtualHost(Constant.VIRTUAL_HOST);
        // 设置用户名
        factory.setUsername(Constant.USER_NAME);
        // 设置密码
        factory.setPassword(Constant.PASSWORD);
        // 设置客户端与服务器的通信端口，默认值为5672
        factory.setPort(Constant.PORT);

        boolean autoAck = true;
        Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String task = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + task + "'");
            try {
                doWork(task);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(" [x] Done");
                // 手动确认消息
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        channel.queueDeclare(TASK_QUEUE_NAME, false, false, false, null);
        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {
        });
    }

    private static void doWork(String task) throws InterruptedException {
        System.out.println("task = " + task);
        for (char ch : task.toCharArray()) {
           // if (ch == '.') Thread.sleep(1000);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
